package com.itheima.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.itheima.myannotation.CacheKey;
import com.itheima.myannotation.Cacheable;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

@Aspect
@Component
public class CacheAspect {
    @Resource
    private JedisPool jedisPool;

    @Around("@annotation(cache)")
    public Object cached(ProceedingJoinPoint pjp, Cacheable cache) {
        Jedis jedis = jedisPool.getResource();
        String key = this.getCacheKey(pjp);
        String value = jedis.get(key);
        if(!StringUtils.isEmpty(value)) {
            return this.isJSONArray(value, pjp);
        }
        Object  obj = null;
        try {
            obj = pjp.proceed();
            if(obj == null) {
                return obj;
            }
            value = JSON.toJSONString(obj);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        if(cache.expire() <= 0) {
            jedis.set(key, value);
        } else {
            jedis.setex(key,cache.expire(),value);
        }
        if(obj instanceof List) {
            if(((List)obj).size() > 0) {
                Class<?> entityClazz = ((List)obj).toArray()[0].getClass();
                return JSONArray.parseArray(value, entityClazz);
            }
            return JSONArray.parseArray(value);
        }
        return this.isJSONArray(value, pjp);
    }
    private Object isJSONArray(String value, ProceedingJoinPoint pjp) {
        Object obj = JSONObject.parse(value);
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Type type = signature.getMethod().getGenericReturnType();
        try {
            if (obj instanceof JSONArray) {
                if (ParameterizedType.class.isAssignableFrom(type.getClass())) {
                    Type[] var7 = ((ParameterizedType) type).getActualTypeArguments();
                    int var8 = var7.length;
                    byte var9 = 0;
                    if (var9 < var8) {
                        Type t1 = var7[var9];
                        return JSONArray.parseArray(value, (Class) t1);
                    }
                }
                return null;
            } else {
                return JSON.parseObject(value, Class.forName(type.getTypeName()));
            }
        } catch (ClassNotFoundException | JSONException var11) {
            return null;
        }
    }
    private String getCacheKey(ProceedingJoinPoint pjp) {
        StringBuilder buf = new StringBuilder();
        Signature signature = pjp.getSignature();
        String declaringTypeName = signature.getDeclaringTypeName();
        String name = signature.getName();
        buf.append(declaringTypeName).append(".").append(name);
        Object[] args = pjp.getArgs();
        Annotation[][] pas = ((MethodSignature)signature).getMethod().getParameterAnnotations();
        int length = pas.length;
        for(int i = 0; i < length; ++i) {
            Annotation[] var1 = pas[i];
            int var2 = var1.length;
            for(int var3 = 0; var3 < var2; ++var3) {
                Annotation an = var1[var3];
                if(an instanceof CacheKey) {
                    buf.append("|").append(((CacheKey)an).key()).append("=").append(args[i].toString());
                    break;
                }
            }
        }
        return buf.toString();
    }
}
